package com.ouyunc.gateway.config.oauth.override;

import com.alibaba.fastjson.JSON;
import com.ouyunc.common.base.ResponseResult;
import com.ouyunc.common.constant.enums.ResponseCodeEnum;
import com.ouyunc.gateway.exception.GlobalExceptionConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author fangzhenxun
 * @Description: 未认证异常处理器，没有通诺认证的请求会通过该处理器
 * @Version V1.0
 **/
@Component
public class IServerAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    private static Logger log = LoggerFactory.getLogger(IServerAuthenticationEntryPoint.class);

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        ServerHttpResponse response = exchange.getResponse();
        // 设置编码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        // 设置状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 将信息转换为 JSON  ResponseResult.error(ResponseCodeEnum.UNAUTHORIZED, e.getMessage()
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(JSON.toJSONBytes(ResponseResult.error(ResponseCodeEnum.UNAUTHORIZED, e.getMessage())));
        return response.writeWith(Mono.just(buffer));
    }
}
